package a66weding.com.jiehuntong.common.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.Map;
import java.util.Random;

import a66weding.com.jiehuntong.R;

/**
 * Created by admin on 2016/8/1.
 */
public class Tools {
    private static Context context;
    private static Dialog ad;
    private static TextView tv;

    /**
     * 初始化注入Context对象
     */
    public static void setContext(Context context) {
        Tools.context = context;
    }

    /**
     * @param context
     * @param view
     * @param x           显示的x坐标
     * @param y           显示的y坐标
     * @param width       dialog的宽度
     * @param height      dialog的高度
     * @param animation   显示和消失的动画效果
     * @param cancleAble  是否可以cancle掉
     * @param isAnimation
     * @return
     */
    private static Dialog showDialog(Context context, View view, int x, int y, int width, int height, int animation, boolean cancleAble, boolean isAnimation) {
        Dialog ad;
        if (Build.VERSION.SDK_INT >= 11) {
            ad = new AlertDialog.Builder(context, R.style.alert_dialog).create();
        } else {
            ad = new Dialog(context, R.style.alert_dialog);
        }
        ad.setCancelable(cancleAble);
        WindowManager.LayoutParams lp = ad.getWindow().getAttributes();
        lp.x = x;
        lp.y = y;
        ad.show();
        ad.setContentView(view);
        ad.getWindow().setLayout(width, height);
        ad.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        return ad;
    }

    /**
     * @param context
     * @param view
     * @param x           显示的x坐标
     * @param y           显示的y坐标
     * @param width       dialog的宽度
     * @param height      dialog的高度
     * @param animation   显示和消失的动画效果
     * @param cancleAble  是否可以cancle掉
     * @param isAnimation
     * @return
     */
    private static Dialog showNobackDialog(Context context, View view, int x, int y, int width, int height, int animation, boolean cancleAble, boolean isAnimation) {
        Dialog ad;
        if (Build.VERSION.SDK_INT >= 11) {
            ad = new AlertDialog.Builder(context, R.style.dialog).create();
        } else {
            ad = new Dialog(context, R.style.alert_dialog);
        }
        ad.setCancelable(cancleAble);
        WindowManager.LayoutParams lp = ad.getWindow().getAttributes();
        lp.x = x;
        lp.y = y;
        ad.show();
        ad.setContentView(view);
        ad.getWindow().setLayout(width, height);
        ad.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        return ad;
    }


    /**
     * 弹出提示用户等待的dialog
     */
    public static Dialog showDialog(final Context context) {
        showWaitDialog(context, "请稍等", false);
        return ad;
    }

    /**
     * 弹出提示用户等待的dialog
     */
    public static void showWaitDialog(final Context context, String str) {
        showWaitDialog(context, str, false);
    }

    /**
     * 弹出提示用户等待的dialog
     */
    public static void showWaitDialog(final Context context, String str, boolean canCancle) {
        if (ad == null || !ad.isShowing()) {
            View vv = View.inflate(context, R.layout.dialog_wait, null);
            tv = (TextView) vv.findViewById(R.id.tv);
            if (!Tools.isEmptyStr(str)) {
                tv.setText(str);
            }
            try {
                Activity activity = (Activity) context;
                if(!activity.isFinishing()){
                    ad = showDialog(context, vv, 0, 0, (int) (Tools.getsx() / 1.8), (int) (Tools.getsy() / 6.5), 0, canCancle, false);
                }
            } catch (Exception e){
                e.printStackTrace();
            }

        } else {
            if (!Tools.isEmptyStr(str)) {
                tv.setText(str);
            }
            ad.setCancelable(canCancle);
        }
    }

    /**
     * 弹出提示用户等待的dialog
     */
    public static void showWaitDialogSmall(final Context context, String str, boolean canCancle) {
        if (ad == null || !ad.isShowing()) {
            View vv = View.inflate(context, R.layout.dialog_wait_small, null);
            tv = (TextView) vv.findViewById(R.id.tv);
            ProgressBar progreIv = (ProgressBar) vv.findViewById(R.id.progress1);
            progreIv.setVisibility(View.GONE);
            if (!Tools.isEmptyStr(str)) {
                tv.setText(str);
            }
            ad = showDialog(context, vv, 0, 0, (int) (Tools.getsx() / 1.8), (int) (Tools.getsy() / 6.5), 0, canCancle, false);
        } else {
            if (!Tools.isEmptyStr(str)) {
                tv.setText(str);
            }
            ad.setCancelable(canCancle);
        }
    }

    /**
     * 弹出显示请求结果的dialog
     */
    public static void showResultDialogSmall(final Context context, String str, boolean canCancle) {
        if (ad == null || !ad.isShowing()) {
            View vv = View.inflate(context, R.layout.dialog_wait_small, null);
            ProgressBar progreIv = (ProgressBar) vv.findViewById(R.id.progress1);
            progreIv.setVisibility(View.GONE);
            tv = (TextView) vv.findViewById(R.id.tv);
            tv.setTextSize(context.getResources().getDimension(R.dimen.font_size15));
            if (!Tools.isEmptyStr(str)) {
                tv.setText(str);
            }
            ad = showNobackDialog(context, vv, 0, 0, (int) (Tools.getsx() / 1.8), (int) (Tools.getsy() / 6.5), 0, canCancle, false);
        } else {
            if (!Tools.isEmptyStr(str)) {
                tv.setText(str);
            }
            ad.setCancelable(canCancle);
        }
    }

    /**
     * 弹出请求数据错误的dialog
     */
    public static void showDataErrDialogSmall(final Context context, String str, boolean canCancle) {

        if (ad == null || !ad.isShowing()) {
            View vv = View.inflate(context, R.layout.dialog_dataerror, null);

            if (!Tools.isEmptyStr(str)) {
                tv.setText(str);
            }
            ad = showDialog(context, vv, 0, 0, (int) (Tools.getsx() / 1.8), (int) (Tools.getsy() / 6.5), 0, canCancle, false);
        } else {
            if (!Tools.isEmptyStr(str)) {
                tv.setText(str);
            }
            ad.setCancelable(canCancle);
        }
    }

    public static boolean isEmptyStr(String str) {
        return (str == null || str.trim().length() < 1);
    }

    public static int getsx() {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    public static int getsy() {
        int px = Resources.getSystem().getDimensionPixelSize(Resources.getSystem().getIdentifier("status_bar_height", "dimen", "android"));
        return context.getResources().getDisplayMetrics().heightPixels - px;
    }

    /**
     * 取消等待的dialog
     */
    public static void dismissWaitDialog() {
        if (ad != null)
        ad.dismiss();
        ad=null;
    }

    /**
     * 获取视频缩略图  可能为null 用前先判断
     *
     * @param videoPath
     * @param width
     * @param height
     * @return
     */

    /**
     * 启动一个新的Activity
     *
     * @param from 起始Activity
     * @param to   跳转Activity
     */
    public static void goActivity(Context from, Class<? extends Activity> to, String[] keys, String[] values) {
        Intent in = new Intent(from, to);
        if (keys != null && values != null)
            for (int i = 0; i < keys.length; i++)
                in.putExtra(keys[i], values[i]);
        from.startActivity(in);
    }

    /**
     * 获取随机数
     *
     * @param min
     * @param max
     * @return
     */
    public static int getRandom(int min, int max) {
        Random random = new Random();
        return random.nextInt(max) % (max - min + 1) + min;
    }

    private static Runnable run;
    private static int delaytime;

    public static void startTask(Runnable _run, int _delaytime) {
        run = _run;
        delaytime = _delaytime;
        handler2.postDelayed(runnable, 0);
        // 开始Timer
    }

    public static void finishTask() {
        handler2.removeCallbacks(runnable);           //停止Timer
        run = null;// 提醒回收
    }

    private static Handler handler2 = new Handler();

    private static Runnable runnable = new Runnable() {

        public void run() {
            if (run != null) {
                run.run();
            }
            handler2.postDelayed(this, delaytime);     //postDelayed(this,1000)方法安排一个Runnable对象到主线程队列中
        }
    };

    /*
    *  根据报名判断是否安装
    */
    public static boolean isAppInstalled(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            //System.out.println("没有安装");
            return false;
        } else {
            //System.out.println("已经安装");
            return true;
        }
    }

    public static String Stitching_parameters(String urlStr, Map<String, Object> paramMap)
            throws Exception {
        StringBuffer sb = null;
        //拼接参数
        StringBuilder params = new StringBuilder();
        int i = 0;
        for (String key : paramMap.keySet()) {
            Object value = paramMap.get(key);
            params.append(key);
            params.append("=");
            params.append(value);
            if (i < paramMap.size() - 1) {
                params.append("&");
            }
            i++;
        }
        return urlStr + sb.toString();
    }


    public static void ShowCollectDialog() {
    }

    /**
     * 注册对话框;
     *
     * @param cancleAble
     * @param x
     * @param y
     * @param width
     * @param height
     * @param view
     * @return
     */
    public static Dialog showRegisterDialog(Context context, boolean cancleAble, int x, int y, int width, int height, View view) {
        if (Build.VERSION.SDK_INT >= 11) {
            ad = new AlertDialog.Builder(context, R.style.dialog).create();
        } else {
            ad = new Dialog(context, R.style.alert_dialog);
        }
        ad.setCancelable(cancleAble);
        ad.show();
        ad.setContentView(view);
        ad.getWindow().setLayout(width, height);
        ad.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        return ad;
    }

    public static void showRegisterDialog(View view, Context context) {
        showRegisterDialog(context, true, 0, 0, ((getsx())), (getsy()), view);
    }

    /**
     * 时间按照xx年
     * @param s
     * @return
     */
    public static String[] getStringArray(String s) {
        String[] sourceStrArray = s.split("T");
        return sourceStrArray;
    }

    private ClickListenerInterface clickListenerInterface;
    public interface ClickListenerInterface {

        public void doConfirm();

        public void doCancel();
    }
    public static Dialog showSimpleDialog(Context context, String title, String cancleStr, String confirmStr, final ClickListenerInterface clickListenerInterface) {
        final Dialog dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        dialog.getWindow().setContentView(R.layout.pop_simple_tooltip);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        ((TextView)window.findViewById(R.id.message_tv)).setText(title);
        TextView cancelTv = ((TextView)window.findViewById(R.id.cancel_tv));
        cancelTv .setText(cancleStr);

        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                clickListenerInterface.doCancel();
            }
        });
        TextView confirmTv = ((TextView)window.findViewById(R.id.confirm_tv));
        confirmTv.setText(confirmStr);
        confirmTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                clickListenerInterface.doConfirm();
            }
        });
        return dialog;
    }

}
